package cn.com.liuxiaoluxx.cloud.api.config.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.com.liuxiaoluxx.cloud.facade.pojo.AuthUser;
import cn.com.liuxiaoluxx.cloud.facade.pojo.UserRole;
import cn.com.liuxiaoluxx.cloud.facade.service.user.UserService;
import lombok.extern.slf4j.Slf4j;

/**
 * The type IntelliJ IDEA.
 * <p>
 *
 * @author liuxiaolu
 * @date 2020/9/18
 */
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    private final UserService userService;

    public MyShiroRealm(UserService userService) {
        this.userService = userService;
    }

    /**
     * 权限授权
     *
     * @param principals 当前登录的实体
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        AuthUser userInfo = (AuthUser) principals.getPrimaryPrincipal();
        for (UserRole sysRole : userService.findSysRoleListByUsername(userInfo.getName())) {
            authorizationInfo.addRole(sysRole.getRoleCode());
        }
        log.info("用户[{}]授权成功", userInfo.getName());
        return authorizationInfo;
    }

    /**
     * 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。
     *
     * @param token token
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        log.info("对用户[{}]进行登录验证..验证开始", usernamePasswordToken.getUsername());
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        AuthUser user = userService.authUser(usernamePasswordToken.getUsername(),
                                             String.valueOf(usernamePasswordToken.getPassword()));
        log.info("对用户[{}]进行登录验证..验证通过", usernamePasswordToken.getUsername());
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}

